import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Badge, Space, Table, Tooltip, message, Button } from 'antd';
import {
  getApiLoginRecordDetailById as DetailRecord,
  postApiLoginRecordByIndexByLimitPagedList as PagedList
} from '@/services/furion-cms/loginRecord';
import React, { useRef, useState } from 'react';

import { BlackOptions } from './components/logOption';
import DetailViewer from './components/logDetail';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { SuccessOrError } from './components/stateTags';
import styles from './index.less';
import { useIntl } from 'umi';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

const LoginRecordTable: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const AccessButton = useCustomAccess(Button);

  const [detailModalVisible, handelDetailModalVisible] = useState<boolean>(false);
  const [loadingVisible, handelLoadingVisible] = useState<boolean>(false);
  const [detailRecord, setDetailRecord] = useState<API.LoginRecordDetailDto | undefined>({});

  const getDetailRecord = async (id: any) => {
    handelLoadingVisible(true);
    try {
      const { data } = await DetailRecord({ id });
      setDetailRecord(data);
      handelDetailModalVisible(true);
    } catch { }
    handelLoadingVisible(false);
  }

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.LoginRecordDto>[] = [
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.loginTime',
        defaultMessage: '登录时间'
      }),
      dataIndex: 'loginTime',
      sorter: true,
      valueType: 'dateRange',
      render: (dom, entity) => {
        return entity.loginTime;
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.host',
        defaultMessage: 'Ip地址'
      }),
      sorter: true,
      copyable: true,
      ellipsis: true,
      dataIndex: 'host',
      render: (dom, entity) => {
        const { hasBlacklist, host: ipAddress } = entity;
        if (hasBlacklist) {
          return <Tooltip title={intl.formatMessage({
            id: 'pages.loginRecord.blacklist.tag',
            defaultMessage: 'Ip地址「{ipAddress}」已被加入黑名单',
          }, { ipAddress })}><Badge status="error" text={(<span style={{ display: 'inline-block' }}>{dom}</span>)} /></Tooltip>
        }
        else {
          return <Badge status="default" text={(<span style={{ display: 'inline-block' }}>{dom}</span>)} />;
        }
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.account',
        defaultMessage: '账号'
      }),
      dataIndex: 'account',
      sorter: true,
      copyable: true,
      search: false
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.refererUrl',
        defaultMessage: '请求来源'
      }),
      dataIndex: 'refererUrl',
      ellipsis: true,
      search: false
    },
    {
      title: intl.formatMessage({
        id: 'pages.loginRecord.result',
        defaultMessage: '结果'
      }),
      dataIndex: 'result',
      ellipsis: true,
      search: false,
      render: (dom, entity) => {
        // return `${entity.result} ${entity.errorMessage}`;
        return <SuccessOrError key="loginResult" success={entity.errorMessage === ""}>
          {entity.errorMessage || intl.formatMessage({
            id: 'pages.loginRecord.result.success',
            defaultMessage: '登录成功'
          })}
        </SuccessOrError>
      }
    },
    {
      title: intl.formatMessage({
        id: 'pages.searchTable.titleOption',
        defaultMessage: '操作'
      }),
      dataIndex: 'option',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <AccessButton key="getDetail"
          code={PermissionsDefinition.LoginAuditLogs.Details}
          type="link"
          onClick={() => {
            getDetailRecord(record.id);
          }}
        >
          {intl.formatMessage({
            id: 'pages.common.detail',
            defaultMessage: '详情'
          })}
        </AccessButton>,
        <BlackOptions key="blackWhiteOption" hasBlacklist={record.hasBlacklist} ipAddress={record.host} callback={() => actionRef.current?.reload()} />,
      ],
    },
  ];

  return (
    <PageContainer className={styles.main}
      breadcrumbRender={false}>
      <ProTable<API.LoginRecordDto>
        pagination={{
          pageSize: 10,
          showSizeChanger:true
        }}
        actionRef={actionRef}
        rowKey="id"
        search={{ filterType: "light" }}
        request={(params, sort, filter) => {
          handelLoadingVisible(true);
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sort, filter);
          // 转换固定的参数
          const { current, pageSize, loginTime } = params;
          const [StartTime, EndTime] = loginTime || [];
          // 删除无效参数
          delete params.current;
          delete params.pageSize;
          delete params.loginTime;
          // 发起请求
          return PagedList({
            index: (current || 1),
            limit: (pageSize || 20),
            StartTime,
            EndTime,
            ...params
          }, sort).then(result => {
            const { list: data, total } = result.data || {};
            return {
              data,
              success: result.success,
              total
            }
          }).finally(() => handelLoadingVisible(false));
        }}
        columns={columns}
        loading={loadingVisible}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        // tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
        //   <Space size={24}>
        //     <span>
        //       {intl.formatMessage({
        //         id: 'pages.common.batchSelected',
        //         defaultMessage: '已选 {count} 项'
        //       }, { count: selectedRowKeys.length })}
        //       <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
        //         {intl.formatMessage({
        //           id: 'pages.common.cancelSelected',
        //           defaultMessage: '取消选择'
        //         })}
        //       </a>
        //     </span>
        //   </Space>
        // )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a onClick={() => message.warning('未实现')}>{intl.formatMessage({
                id: 'pages.common.batchExport',
                defaultMessage: '导出数据'
              })}</a>
            </Space>
          );
        }}
      />
      <DetailViewer modalVisible={detailModalVisible}
        onCancel={() => handelDetailModalVisible(false)}
        onUpdate={() => actionRef.current?.reload()}
        recored={detailRecord} />
    </PageContainer>
  );
};

export default LoginRecordTable;
